using System;
using Microsoft.SPOT;
using GHIElectronics.NETMF.Hardware;
using System.Threading;

namespace AstroX
{
    public class TemperatureController
    {
        ThermometerWatcher insideWatcher;
        ThermometerWatcher outsideWatcher;
        OneWire ow;
        public TemperatureController()
        {
            ow = new OneWire(AstoXPinMap.IntTempPin);


            ow.Search_Restart();
            byte[] id1 = new byte[8];
            ow.Search_GetNextDevice(id1);
            byte[] id2 = new byte[8];
            ow.Search_GetNextDevice(id2);

            Thread t = new Thread(() =>
                {
                    while (FlightControl.CurrentPhase != FlightPhases.Shutdown)
                    {
                        Program.Print("Temp 1 is" + GetTemp(id1));
                        Program.Print("Temp 2 is" + GetTemp(id2));
                    }
                });
            t.Start();

        }

        public float GetTemp(byte[] address)
        {
            long data = 0;
            ow.Reset();
            //Select
            ow.WriteByte(DS18B20.MatchROM);
            for (int i = 0; i < 8; i++)
            {
                ow.WriteByte(address[i]);
            }
            ow.WriteByte(DS18B20.StartTemperatureConversion);
            while (ow.ReadByte() == 0) { }
            ow.Reset();
            ow.WriteByte(DS18B20.MatchROM);
            for (int i = 0; i < 8; i++)
            {
                ow.WriteByte(address[i]);
            }
            ow.WriteByte(DS18B20.ReadScratchPad);

            data = ow.ReadByte(); // LSB 
            data |= (ushort)(ow.ReadByte() << 8); // MSB            
            return (float)(32.0 + (9.0 / 5.0) * (data / 16.0));
        }


    }
}
